﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using log4net;

public partial class searchCar : System.Web.UI.Page
{
    private const int PAGE_SIZE = 10;


    private static readonly ILog logger = LogManager.GetLogger(typeof(searchCar).Name);
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
                LoadToDDL();
                LoadToRepeater();
                lblMsg.Visible = false;
                btnFirst.Enabled = btnPrev.Enabled = false;
            }
        }
        catch (Exception ex)
        {
            lblMsg.Text = Constants.ERROR_MSG;
            lblMsg.Visible = true;
            if (logger.IsErrorEnabled) { logger.Error(ex.Message); }
        }
    }



    /// <summary>
    /// LoadToDDL
    /// </summary>
    private void LoadToDDL()
    {
        IList<ParkingFloor> listFloor = new ParkingFloor().GetAll();
        ddlFloor.DataSource = listFloor;
        ddlFloor.DataTextField = "Name";
        ddlFloor.DataValueField = "Name";
        ddlFloor.DataBind();


        IList<CardType> listCard = new CardType().GetAll();
        ddlCardType.DataSource = listCard;
        ddlCardType.DataTextField = "Name";
        ddlCardType.DataValueField = "ID";
        ddlCardType.DataBind();
    }

    /// <summary>
    /// Load to Rpt
    /// </summary>
    private void LoadToRepeater()
    {
        string parkingFloor = string.Empty;
        Guid carTypeId=Guid.Empty;
        string plat = string.Empty;
        DateTime fromEntry=DateTime.MinValue;
        DateTime toEntry = DateTime.MinValue;
        DateTime fromExit = DateTime.MinValue;
        DateTime toExit = DateTime.MinValue;
        bool chkPlat=false;

        #region Search condition
        if (IsPostBack)
        {
            //Ham xe
            if (!string.IsNullOrEmpty(ddlFloor.SelectedValue))
            {
                parkingFloor = ddlFloor.SelectedValue.ToString();
            }

            //Card type
            if (!string.IsNullOrEmpty(ddlCardType.SelectedValue))
            {
                carTypeId = new Guid(ddlCardType.SelectedValue);
            }

            //plat
            if (!string.IsNullOrEmpty(txtPlat.Text.Trim()))
            {
                plat = txtPlat.Text.Trim();
            }

            //fromEntry
            if (!string.IsNullOrEmpty(txtFromEntry.Text.Trim()))
            {
                fromEntry = DateTime.ParseExact(txtFromEntry.Text.Trim(), Constants.DATE_PATTERN, null);
            }

            //toEntry
            if (!string.IsNullOrEmpty(txtFromEntry.Text.Trim()))
            {
                toEntry = DateTime.ParseExact(txtToEntry.Text.Trim(), Constants.DATE_PATTERN, null);
            }

            //fromExit
            if (!string.IsNullOrEmpty(txtFromExit.Text.Trim()))
            {
                fromExit = DateTime.ParseExact(txtFromExit.Text.Trim(), Constants.DATE_PATTERN, null);
            }

            //toExit
            if (!string.IsNullOrEmpty(txtToExit.Text.Trim()))
            {
                toExit = DateTime.ParseExact(txtToExit.Text.Trim(), Constants.DATE_PATTERN, null);
            }

            //checkbox
            if (chkCheck.Checked)
            {
                chkPlat = true;
            }
        } 
        #endregion

        string sql = "[SearchCarPaging]";
        DataTable dt = new DataTable();

        #region parms
        SqlParameter[] parms = new SqlParameter[]
        {
            new SqlParameter("@Page",CurrentPage),
            new SqlParameter("@PageSize",PAGE_SIZE),

            string.IsNullOrEmpty(parkingFloor) ? new SqlParameter("@ParkingFloor", DBNull.Value) :
                                                            new SqlParameter("@ParkingFloor", parkingFloor),

            (carTypeId==Guid.Empty) ? new SqlParameter("@CardTypeID", DBNull.Value) :
                                                            new SqlParameter("@CardTypeID", carTypeId),

           string.IsNullOrEmpty(plat) ? new SqlParameter("@PlateNumber", DBNull.Value) :
                                                            new SqlParameter("@PlateNumber", plat),

            fromEntry==DateTime.MinValue ? new SqlParameter("@EntryFrom", DBNull.Value) :
                                                            new SqlParameter("@EntryFrom", fromEntry),

            toEntry==DateTime.MinValue ? new SqlParameter("@EntryTo", DBNull.Value) :
                                                            new SqlParameter("@EntryTo", toEntry),

            fromExit==DateTime.MinValue ? new SqlParameter("@ExitFrom", DBNull.Value) :
                                                            new SqlParameter("@ExitFrom", fromExit),

            toExit==DateTime.MinValue ? new SqlParameter("@ExitTo", DBNull.Value) :
                                                            new SqlParameter("@ExitTo", toExit)    ,
            
            !chkPlat? new SqlParameter("@PlateDiff",false) :
                                                            new SqlParameter("@PlateDiff", true),
            new SqlParameter("@NotExit",chkNotExit.Checked)     

        }; 
        #endregion

        dt = SqlHelper.ExecuteDataset(CommandType.StoredProcedure, sql, parms).Tables[0];

        rptSearch.DataSource = dt;
        rptSearch.DataBind();

        if (dt.Rows.Count == 0)
        {
            lblResult.Text = "Không có xe nào";
            lblResult.Visible = true;
            pnResult.Visible = false;
        }
        else {
            lblResult.Visible = true;
            pnResult.Visible = true;
        }

        GetTotalPage(parkingFloor, carTypeId,
        plat, fromEntry, toEntry,
        fromExit, toExit,chkPlat);
    }

    private void GetTotalPage(string parkingFloor, Guid carTypeId,
        string plat, DateTime fromEntry, DateTime toEntry,
        DateTime fromExit, DateTime toExit,bool chkPlat)
    {

        #region parms
        SqlParameter[] parms = new SqlParameter[]
        {

            string.IsNullOrEmpty(parkingFloor) ? new SqlParameter("@ParkingFloor", DBNull.Value) :
                                                            new SqlParameter("@ParkingFloor", parkingFloor),

            (carTypeId==Guid.Empty) ? new SqlParameter("@CardTypeID", DBNull.Value) :
                                                            new SqlParameter("@CardTypeID", carTypeId),

           string.IsNullOrEmpty(plat) ? new SqlParameter("@PlateNumber", DBNull.Value) :
                                                            new SqlParameter("@PlateNumber", plat),

            fromEntry==DateTime.MinValue ? new SqlParameter("@EntryFrom", DBNull.Value) :
                                                            new SqlParameter("@EntryFrom", fromEntry),

            toEntry==DateTime.MinValue ? new SqlParameter("@EntryTo", DBNull.Value) :
                                                            new SqlParameter("@EntryTo", toEntry),

            fromExit==DateTime.MinValue ? new SqlParameter("@ExitFrom", DBNull.Value) :
                                                            new SqlParameter("@ExitFrom", fromExit),

            toExit==DateTime.MinValue ? new SqlParameter("@ExitTo", DBNull.Value) :
                                                            new SqlParameter("@ExitTo", toExit)       ,
     
            !chkPlat? new SqlParameter("@PlateDiff",false) :
                                                            new SqlParameter("@PlateDiff", true),

            new SqlParameter("@NotExit",chkNotExit.Checked)
        };
        #endregion

        int totalPage = 0;

        string sql = "[SearchCarPagingTotal]";

        int records = (int)SqlHelper.ExecuteScalar(CommandType.StoredProcedure, sql, parms);
        lblResult.Text = String.Format("Tổng số records: {0}", records);

        totalPage = records / PAGE_SIZE;
        //kiem tra co sang trang ko
        int div = records % PAGE_SIZE;
        if (div != 0)
        {
            totalPage++;
        }

        btnFirst.Enabled = btnPrev.Enabled = btnNext.Enabled = btnLast.Enabled = (totalPage > 1);


        //Set paging
        ltrPage.Text = String.Format("{0}/{1}", CurrentPage, totalPage);
        ViewState["TotalPage"] = totalPage;
    }


    #region Paging
    protected void btnLast_Click(object sender, ImageClickEventArgs e)
    {
        CurrentPage = int.Parse(ViewState["TotalPage"].ToString());
        LoadToRepeater();
        btnLast.Enabled = btnNext.Enabled = false;
        btnFirst.Enabled = btnPrev.Enabled = true;
    }
    protected void btnFirst_Click(object sender, ImageClickEventArgs e)
    {
        CurrentPage = 1;
        LoadToRepeater();
        btnLast.Enabled = btnNext.Enabled = true;
        btnFirst.Enabled = btnPrev.Enabled = false;
    }
    protected void btnPrev_Click(object sender, ImageClickEventArgs e)
    {
        CurrentPage--;
        LoadToRepeater();
        if (int.Parse(ViewState["TotalPage"].ToString()) == 1)
        {
            btnLast.Enabled = btnNext.Enabled = true;
            btnFirst.Enabled = btnPrev.Enabled = false;
        }
    }
    protected void btnNext_Click(object sender, ImageClickEventArgs e)
    {
        CurrentPage++;
        LoadToRepeater();
        if (CurrentPage == int.Parse(ViewState["TotalPage"].ToString()))
        {
            btnLast.Enabled = btnNext.Enabled = false;
            btnFirst.Enabled = btnPrev.Enabled = true;
        }

    }

    private int CurrentPage
    {
        get
        {
            object objPage = ViewState["_CurrentPage"];
            int _CurrentPage = 1;
            if (objPage == null)
            {
                _CurrentPage = 1;
            }
            else
            {
                _CurrentPage = (int)objPage;
            }
            return _CurrentPage;
        }
        set { ViewState["_CurrentPage"] = value; }
    }
    #endregion
    protected void btnSearch_Click(object sender, ImageClickEventArgs e)
    {
        try
        {
            LoadToRepeater();
        }
        catch (Exception ex)
        {
            lblMsg.Text = Constants.ERROR_MSG;
            lblMsg.Visible = true;
            if (logger.IsErrorEnabled) { logger.Error(ex.Message); }
        }
    }
    protected void rptSearch_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Literal ltrId = (Literal)e.Item.FindControl("ltrId");
            HiddenField hdnId = (HiddenField)e.Item.FindControl("hdnId");
            ltrId.Text = hdnId.Value;
        }
    }
}